<?php

include "DBConnection.php";
include "model/Car.php";
include "model/TrackForList.php";
include "model/TrackList.php";
include "model/TrackData.php";
include "model/User.php";

$connection = new DBConnection();
$connection -> connect();

$userID = $_REQUEST['userID'];

$statement = $connection -> query("SELECT track.id, track.date, user.id AS userID, user.name AS userName, car.id AS carID, car.name AS carName, car.horsepower AS carHorsePower
FROM track
INNER JOIN user_car ON track.user_car_id = user_car.id
INNER JOIN car ON user_car.car_id = car.id
INNER JOIN user ON user_car.user_id = user.id
WHERE user.id = ?", array($userID));

if ($statement) {
	$trackID = -1;

	$trackList = new TrackList();
	$trackList -> init();

	$jsonString = "{ \"tracks\" : [ \n";

	while ($result = $statement -> fetchObject()) {
		$currentTrack = new TrackForList();
		$currentTrack -> id = (int)$result -> id;
		$currentTrack -> date = $result -> date;

		//the user
		$currentUser = new User();
		$currentUser -> userID = (int)$result -> userID;
		$currentUser -> userName = $result -> userName;

		// the car
		$currentCar = new Car();
		$currentCar -> carID = (int)$result -> carID;
		$currentCar -> carName = $result -> carName;
		$currentCar -> carHorsePower = $result -> carHorsePower;

		// build track object
		$currentTrack -> user = $currentUser;
		$currentTrack -> car = $currentCar;

		$trackList -> add($currentTrack);
		
		array_push($trackList->tracks, $currentTrack);

		$jsonString = $jsonString . json_encode($currentTrack) . ",";
	}
	$jsonString = substr($jsonString, 0, -1);

	$jsonString = $jsonString . " ] \n }";

//	echo json_encode($trackList);
//	echo "----------------";
	echo $jsonString;
}
?>